#include "Controls.h"

Controls * Controls::controlsInstance = NULL;

Controls::Controls()
{
	ClearKeys(); //TODO: move this to initilise if we still need it

}

Controls::~Controls(void)
{
	dinkeyboard->Unacquire();    // make sure the keyboard is unacquired
    din->Release();    // close DirectInput before exiting
}

Controls * Controls::Instance()
{
	if ( controlsInstance == 0 )
		controlsInstance = new Controls();

	return controlsInstance;
}

void Controls::Initialise(HINSTANCE hInstance, HWND hWnd)
{

	    // create the DirectInput interface
    DirectInput8Create(hInstance,    // the handle to the application
                       DIRECTINPUT_VERSION,    // the compatible version
                       IID_IDirectInput8,    // the DirectInput interface version
                       (void**)&din,    // the pointer to the interface
                       NULL);    // COM stuff, so we'll set it to NULL

    // create the keyboard device
    din->CreateDevice(GUID_SysKeyboard,    // the default keyboard ID being used
                      &dinkeyboard,    // the pointer to the device interface
                      NULL);    // COM stuff, so we'll set it to NULL

    dinkeyboard->SetDataFormat(&c_dfDIKeyboard); // set the data format to keyboard format

    // set the control you will have over the keyboard
    dinkeyboard->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_BACKGROUND);

}


void Controls::CaptureKeys(void)
{
	dinkeyboard->Acquire();    // get access if we don't have it already

	dinkeyboard->GetDeviceState(256, (LPVOID)currentKeys);    // fill keystate with values

	for (int i = 0; i<256; i++ )
	{
		if ( (currentKeys[i] == 0x00) && (previosKeys[i] == 0x80) ) //key has been released
		{
			pressedKeys.push_back( (BYTE)i );
		}

		previosKeys[i] = currentKeys[i];
	}


}

BYTE Controls::GetPressedKey()
{
	BYTE result;

	if( !pressedKeys.empty() )
	{
		result = pressedKeys.front();
		pressedKeys.pop_front();
	}
	else
	{
		result = 0;
	}

	return result;
}

void Controls::ClearKeys()
{
	for(int i = 0; i < 256; i++)
	{
		currentKeys[i] = 0;
	} 
}